package com.zb.oauth.service.Impl;

import com.zb.oauth.service.MyAuthService;
import com.zb.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Map;

@Service
public class MyAuthServiceImpl implements MyAuthService {

  @Autowired
  private RestTemplate restTemplate;

  @Override
  public AuthToken login(String username, String passwd, String clientId, String clientSecret) {
    String url = "http://auth-server/oauth/token";

    MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.add("grant_type", "password");
    body.add("username", username);
    body.add("password", passwd);

    MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
    header.add("authorization", this.getHeaderData(clientId, clientSecret));//
    //发起远程调用http 请求
    ResponseEntity<Map> responseEntity = null;
    try {
      responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(body, header), Map.class);
    } catch (RuntimeException e) {
      e.printStackTrace();
      throw new RuntimeException("调用/oauth/token异常");
    }
    Map<String, String> result = responseEntity.getBody();
//    System.out.println(result+"===========================");
    AuthToken authToken = new AuthToken();
    authToken.setAccessToken(result.get("access_token"));
    authToken.setRefreshToken(result.get("refresh_token"));
    authToken.setJti(result.get("jti"));
    return authToken;
  }

  private String getHeaderData(String clientId, String clientSecret) {
    //Basic emhvbmdibzp6aG9uZ2Jv
    //      emhvbmdibzp6aG9uZ2Jv
    String str = clientId + ":" + clientSecret;
    byte[] encode = Base64Utils.encode(str.getBytes());
    try {
      return "Basic " + new String(encode, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return "";
  }


}
